<?php 
namespace Wdl\helper;

class webHelper{

    static function bindShopid(){
        global $_W;
        if($_W['isfounder']==1){
            return 0;//平台创始人 不受shopid限制
        }else{
            $shop = pdo_fetch("select * from ".tablename('kbwdl_shop')." where uniacid=:uniacid and uid=:uid", 
            ['uniacid'=> webHelper::bindUniacid(), 'uid'=> $_W['uid']]);
            if($shop)
                return $shop['id'];
            else 
                return -1; //不可管理任何shopid相关的数据
        }

    }
    static function bindUniacid()
    {
        global $_W;
        if( !empty($_W['current_module']['config']['xcxid'])){
            return $_W['current_module']['config']['xcxid'];
        }else{
            return $_W['uniacid'];
        }
    }
    static function table_list_data($table, $condition, $params, $order = "`id` DESC", $psize=15)
    {
        global $_GPC;
        $pindex = max(1, intval($_GPC['page']));
        
        $sql = 'SELECT COUNT(*) FROM ' . tablename( $table) . $condition;
        $total = pdo_fetchcolumn($sql, $params);
        if (!empty($total)) {
            $sql = 'SELECT * FROM ' . tablename( $table ) 
                            . $condition 
                            . ' ORDER BY '.$order.'  LIMIT '
                            . ($pindex - 1) * $psize . ',' . $psize;
            $list = pdo_fetchall($sql, $params);
            $pager = pagination($total, $pindex, $psize);
        }
        return [
            'total' => $total,
            'list' => $list,
            'pager' => $pager,
        ];
    }

    static function quans()
    {
        global $_W, $_GPC;
        $uniacid = webHelper::bindUniacid();
        $quan = pdo_fetchall("select * from " . tablename("kbwdl_area") . " where uniacid='$uniacid' and type=2 and disabled=0  order by orderid desc ,id desc");
        if (!empty($quan)) {
            $tmp = array();
            foreach ($quan as $key => $q) {
                $tmp[$q['area']][] = $q['name'];
            }          
            return $tmp ;           
        }
        return [];
    }
    static function citys()
    {
        $config = webHelper::fetch_place_data('setting', 'display');
        return [1=> !empty($config['cityname']) ? $config['cityname'] : '默认'];
    }
    //获取二手房的配置参数
    static function sechouse_form_data()
    {
        $data = webHelper::fetch_place_data('formdata', 'sechouse');
        foreach($data as $key=> $item){
            if(!in_array($key, self::sechouse_fields()))
                continue;

            $tmp = explode(",", $item);
            $arr = [];
            foreach($tmp as $val){
                $arr[] = "$val|$val";
            }
            $data[$key] = implode(",", $arr);
        }
        //处理jingyin字段
        $jingyin = explode("\n", $data['jingyin']);
        $tmp = [];
        foreach($jingyin as $k => $val){
            $str = explode(":", $val);
            $tmp[$str[0]] = explode(",", isset($str[1]) ? $str[1]: "");
        }
        $data['jingyin'] = $tmp;
        unset($tmp, $val,$key, $k);
        return $data;
    }
    static function zhutype_map_type($type = 0)
    {
        $m = self::house_type();
        $op = 'sechouse';
        foreach($m as $key=> $item){
            if($item['zhutype'] == $type){
                $op = $key;
                break;
            }
        }
        return $op;
    }
    static function zhutypeLabel($zhutype='')
    {
        $label = [
            0=> '二手房',
            2=> '租房',
            3=> '新房',
            4=> '商铺',
            7=> '厂房',
            8=> '仓库',
            9=> '写字楼',
        ];
        if($zhutype=='') return $label;
        
        return isset($label[$zhutype]) ? $label[$zhutype] : "未知";
    }
    static function house_type()
    {
        return [
            'sechouse'=>   ['name'=> '二手房',  'zhutype'=>0,'rent_type'=>0],
            'newhouse'=> ['name'=> '新房',   'zhutype'=>3,'rent_type'=>0],
            'chuzu'=> ['name'=> '租房',   'zhutype'=>2,'rent_type'=>0],
            'pumian'=>['name'=> '商铺',  'zhutype'=>4,'rent_type'=>0],
            'changfang'=>['name'=> '厂房',   'zhutype'=>7,'rent_type'=>0],
            'cangku'=> ['name'=> '仓库',   'zhutype'=>8,'rent_type'=>0],
            'xiezilou'=>['name'=> '写字楼', 'zhutype'=>9,'rent_type'=>0],           
        ];
    }
    static function sechouse_fields()
    {
        return [
            'newhouse_tese'=> ['name'=>'新房标签', 'value'=>''],
            'disposition' =>['name'=>'二手房标签', 'value'=>''] ,
            'housetype' => ['name'=>'二手房类型', 'value'=>''],
            'rent_zhu' => ['name'=>'租房业态配套', 'value'=>''], 
            'rent_zhu_all' => ['name'=>'整体配套', 'value'=>''], 
            'rent_zhu_mensuo'=> ['name'=>'门锁特色', 'value'=>''],
            'rent_zhu_chufang'=>['name'=>'厨房配套', 'value'=>''],
            'rent_zhu_keting'=>['name'=>'客厅配套', 'value'=>''],
            'rent_zhu_weishengjian'=> ['name'=>'卫生间配套', 'value'=>''],
            'rent_zhu_woshi'=> ['name'=>'卧室配套', 'value'=>''],          
            'chaoxiang' => ['name'=>'房屋朝向', 'value'=>''],
            'zhaungxiu' => ['name'=>'装修状态', 'value'=>''], 
            'oldage'=>['name'=>'房源新旧', 'value'=>''],      
            'changfang_type'=>['name'=>'厂房类型', 'value'=>''],
            'changfang_jiegou'=>['name'=>'厂房结构', 'value'=>''],
            'rent_changfang'=>['name'=>'厂房配套', 'value'=>''],
            'cangku_type'=> ['name'=>'仓库类型', 'value'=>''],
            'cangku_used'=>['name'=>'仓库用途', 'value'=>''],                
            'sptype' =>['name'=>'商铺类型', 'value'=>''] , 
            'pumian_tese'=> ['name'=>'商铺配套', 'value'=>''],             
            'hangye'=>['name'=>'业态大分类', 'value'=>''],  
             
        ];
    }
    static function str_to_array($str)
    {
        $arr = [];
        if($str){
            $strs = explode(",", $str);
            foreach($strs as $val){
                $tmp = explode("|", $val);
                $arr[$tmp[0]] = isset($tmp[1]) ? $tmp[1] : $tmp[0];
            }
            
        }
        return $arr;   
         
    }
    static function  WebUrl($do, $query = array()) {
        global $_W;
		$query['do'] = $do;
		$query['module_name'] = strtolower( $_W['current_module']['name']);

		return wurl('site/entry', $query);
	}
   static function update_place_data( $modulename, $confkey, $confvalue = array(), $placeid=0){
        global  $_GPC, $_W; 
        $uniacid = webHelper::bindUniacid(); 
        if(empty($confvalue)){
            $conf_value = $_GPC[$confkey];
        }else{
            $conf_value = $confvalue;
        }
        //处理值
        if(is_array($conf_value))
        foreach($conf_value as $k => $val){
            if(!is_array($val) && !in_array($k, ['privacy','companydescript']))
                $conf_value[$k] = str_replace(['，'],',', trim($val));
        }
        
        $has = pdo_fetch("select * from ".tablename("kbwdl_config")." where placeid='$placeid' and confkey='$confkey' and uniacid='$uniacid' and module='$modulename'");
        $data = array(
                'placeid'=>$placeid, 
                'uniacid'=>$uniacid, 
                'uid'=>$_W['uid'],
                'module'=>$modulename,
                'confkey'=>$confkey, 
                'conf_value'=>iserializer($conf_value)  
            );
        if(empty($has)){
            pdo_insert("kbwdl_config", $data );
        }else{
            pdo_update("kbwdl_config", $data, array('id'=> $has['id']) );
        }
        return true;
    }
    static function fetch_place_data($modulename, $confkey='',  $placeid=0 ){
        global  $_GPC, $_W; 
        $uniacid = webHelper::bindUniacid();    
       
        $sqladd = '';
        if($confkey!=''){
            $sqladd = " and confkey='$confkey' ";
        }
        $data = [];
        $ret = pdo_fetchall("select * from ".tablename("kbwdl_config")." where placeid='$placeid' $sqladd and uniacid='$uniacid' and module='$modulename' order  by id desc");
        foreach($ret as $row){
            $data[ $row['confkey'] ] = iunserializer ($row['conf_value'] );
        }
        if($confkey && isset($data[$confkey])){
            return $data[$confkey];
        }
        return $data;
    }

    static function fourm_delete($id)
    {
        $category = pdo_fetch("SELECT id, parentid, type FROM ".tablename('kbwdl_forums')." WHERE id = '$id'");
        if (empty($category)) {
            return false;
        }        
        pdo_delete('kbwdl_forums', array('id' => $id));
        return true;
    }
    static function fourm_change_status($cd_type){
        global $_W, $_GPC;
        $id = intval($_GPC['id']);
        $category_exist = pdo_get('kbwdl_forums', array('id' => $id, 'uniacid' => webHelper::bindUniacid()));
        if (!empty($category_exist)) {
            $status = $category_exist['disabled'] == 1 ? 0 : 1;
            $result = pdo_update('kbwdl_forums', array('disabled' => $status), array('id' => $id));
            if ($result) {
                return true;
            }  
        }  
        return false;
    }
    /** 
     * 更新分类操作
     */
    static function fourm_post( $cd_type=0)
    {
        global $_W, $_GPC;
        $parentid = intval($_GPC['parentid']);
	    $id = intval($_GPC['id']);
        $uniacid = webHelper::bindUniacid();
        
        if (!empty($id)) {
            $category = pdo_fetch("SELECT * FROM ".tablename('kbwdl_forums')." WHERE id = '$id' AND uniacid = '{$uniacid}' and type={$cd_type}");
            if (empty($category)) {
                //itoast('分类不存在或已删除', '', 'error');
                return ['code'=>1, 'msg'=> '分类不存在或已删除'];
            }
        
        } else {
            $category = array(
                'orderid' => 0,
                'css' => array(),
            );
        }
        if (!empty($parentid)) {
            $parent = pdo_fetch("SELECT id, fname as name,fans FROM ".tablename('kbwdl_forums')." WHERE id = '$parentid' and type={$cd_type}");
            if (empty($parent)) {
               // itoast('抱歉，上级分类不存在或是已经被删除！', $this->createWebUrl('category', array('op' => 'display')), 'error');
                return ['code'=>1, 'msg'=> '抱歉，上级不存在或已被删除！'];
            }
            $fans_type = $parent['fans'];
        }else{
                $parent['id'] = 0;
                $parent['name'] = '作为一级分类';
                $fans_type = $_GPC['fans'];
        }
    
        if (checksubmit('submit')) {
            if (empty($_GPC['cname'])) {
               // itoast('抱歉，请输入分类名称！', '', '');
               return ['code'=>1, 'msg'=> '抱歉，请输入名称！'];
            }
            $data = array(
                'uniacid' => $uniacid,
                'fname' => $_GPC['cname'],
                'orderid' => intval($_GPC['displayorder']),
                'parentid' => intval($parentid),
                'thumb' => trim($_GPC['thumb']),
                'thumb_active' =>  trim($_GPC['thumb_active']),
                'desc' => urlencode($_GPC['description']) ,
                'type' => $cd_type,			 
                'disabled' => intval($_GPC['enabled']),
                'fans' => $fans_type,
                'islink'=> intval($_GPC['islink']),
            );
            
            if (!empty($id)) {
                unset($data['parentid']);
                pdo_update('kbwdl_forums', $data, array('id' => $id));
            } else {
                pdo_insert('kbwdl_forums', $data);
                $id = pdo_insertid();
                
            }
           return ['code'=> 0, 'msg'=> '抱歉，请输入名称！'];;
        }
    }

    /**
     * 
     * @param   $config
     * @param   $item
     * @return  
     */
    static public function format_message($config, $item){
    /**文本消息*/
        $text = $content = $ext = $name =  '';                 
        if($item['msgType']=='TIMTextElem'){                
            $temp = json_decode($item['msgContent']);                
            $text = $temp->Text;    


        }else if($item['msgType']=='TIMCustomElem') {
            /**自定义消息  */              
            $temp = json_decode($item['msgContent']);                
            if($temp->Text){
                $text = $temp->Text; 
                $content = htmlspecialchars_decode($temp->Data );
                $ext = $temp->Ext;
            }  
        }else if($item['msgType'] == 'TIMImageElem'){

            $temp = json_decode( $item['msgContent']  );  
            $text = $temp->Text; 
            $content =  html_entity_decode($temp->Data ) ;  
            $ext = tomedia($temp->Ext);
        }else{
            $temp = json_decode( $item['msgContent']  );  
            $text = $temp->Text; 
            $content =  html_entity_decode($temp->Data ) ;  
            $ext = $temp->Ext;
        }
            //自已发的还是别人
        if($config['fromAccount'] == $item['From_Account']){                        
            $cssT = 'aui-chat-right';                
            $thumb = $config['fromAccountPic'];   
            $name =    $config['fromAccountName'];             
        }else{
            $cssT = 'aui-chat-left';                
            $thumb = $config['toAccountPic'];
            $name = $config['toAccountName'];   
        }  
        return array(
            'id'=> $item['id'],
            'whocss'=> $cssT,
            'thumb'=> tomedia( $thumb),
            'name'=> $name,
            'addtime'=> $item['addTime'],
            'content'=>  $text ,
            'Data'=>$content,
            'Ext'=> $ext,  
            'To_Account' =>  $item['To_Account'],
            'msgType' => $item['msgType'],
        );
    }
}